$(document).ready(function() {

    $('#carousel-575751').carousel({
        interval: 4000
    })
    $('#carousel-783283').carousel({
        interval: 4000
    })
    $('#osCarousel').carousel({
        interval: 3000
    })
     $('#datesCarousel').carousel({
        interval: 5000
    })
    

    $('.modal').each(function() {
        var src = $(this).find('iframe').attr('src');

        $(this).find(".btn").on('click', function() {

            $(this).parents(".modal-content").find('iframe').attr('src', '');
            $(this).parents(".modal-content").find('iframe').attr('src', src);

        });

    });
    
	var boxheight = $('.carousel-inner').height();
	var itemlength = $('.item').length;
	var triggerheight = Math.round(boxheight/(itemlength-1.4));
	$('.list-group-item').height(triggerheight);
	
	var clickEvent = false;
	$('#newsCarousel').carousel({
		interval:   4000	
	}).on('click', '.list-group li', function() {
			clickEvent = true;
			$('.list-group li').removeClass('active');
			$(this).addClass('active');		
	}).on('slid.bs.carousel', function(e) {
		if(!clickEvent) {
			var count = $('.list-group').children().length -1;
			var current = $('.list-group li.active');
			current.removeClass('active').next().addClass('active');
			var id = parseInt(current.data('slide-to'));
			if(count == id) {
				$('.list-group li').first().addClass('active');	
			}
		}
		clickEvent = false;
	});

    $(function() {
        $.scrollUp({
            scrollName: 'scrollUp', // Element ID
            topDistance: '300', // Distance from top before showing element (px)
            topSpeed: 300, // Speed back to top (ms)
            animation: 'fade', // Fade, slide, none
            animationInSpeed: 200, // Animation in speed (ms)
            animationOutSpeed: 200, // Animation out speed (ms)
            scrollText: '&uarr; Top &uarr;', // Text for element
            activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
        });
    });

    if ($('#password').length) {
        $('#password').passStrengthify();
    }

    $("#loginSubmit").click(function() {
        $("#loginForm").submit(function(e){
            e.preventDefault();
        $.ajax(
            {
                type: "POST",
                url: baseUrl + "/user/login/",
                data: {
                   'loginEmail' : $("#loginEmail").val(),
                   'loginPassword' : $("#loginPassword").val(),
                   'remember' : (($('#remember').is(":checked")))?$("#remember").val():0
                },
                dataType: "json",
                success: function(data) {
                    
                    if(data.loginStatus == "failed"){
                        $("#loginError").html("<p class='text-danger'>"+data.message+"</p>")
                    } else {
                        window.location = baseUrl + "/index"
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
                
        });
    });

    });



    $("#pollVote").click(function() {
        var choice = $("input[name='pollChoice']:checked").val();
        var pollId = $("#pollId").val();

        if (choice) {
            $.ajax(
                    {
                        type: "GET",
                        url: baseUrl + "/poll/result/pollId/" + pollId + "/choiceId/" + choice,
                        dataType: "json",
                        success: function(data) {
                            $("#pollDisplay").empty();

                            var choicesDiv = "";
                            var className = "";
                            for (var i in data[1]) {
                                var choicePercentage = (data[1][i].count / data[2].sum) * 100;
                                switch (i) {
                                    case "0":
                                        className = " red";
                                        break;
                                    case "1":
                                        className = " blue";
                                        break;
                                    case "2":
                                        className = " green";
                                        break;
                                    case "3":
                                        className = " yellow";
                                        break;
                                }
                                choicesDiv += '<h4>' + data[1][i].pollChoice + '</h4><div class="progress">\n\
<div class="progress-bar' + className + '" role="progressbar" aria-valuenow="' + choicePercentage + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + choicePercentage + '%;">\n\
' + Math.round(choicePercentage * 10) / 10 + '%</div></div>';
                            }
                            $("#pollDisplay").append('<h3>' + data[0].pollQuestion + '</h3>' + choicesDiv + '<div class="pull-right">Total Votes:<strong>' + data[2].sum + '</strong></div>');
                            setCookie("pollId", pollId, 150);
                        },
                        error: function(xhr, ajaxOptions, thrownError)
                        {
                            alert(xhr.status);
                            alert(xhr.responseText);
                            alert(thrownError);
                        }
                    });

        } else {
            $("#pollError").html("<p class='text-danger'>Please select choice!</p>");
        }

    });

    if ($("#pollId").val() == getCookie("pollId")) {
        displayPollResult($("#pollId").val());
    }
    
        addthisevent.settings({
	mouse		: true,
	css		: true,
	outlook		: {show:true, text:"Outlook"},
	google		: {show:true, text:"Google"},
	yahoo		: {show:true, text:"Yahoo"},
	ical		: {show:true, text:"iCal"},
	hotmail		: {show:true, text:"Hotmail"}
});

});
function displayPollResult(pollId) {
    $.ajax(
            {
                type: "GET",
                url: baseUrl + "/poll/result/pollId/" + pollId,
                dataType: "json",
                success: function(data) {
                    $("#pollDisplay").empty();

                    var choicesDiv = "";
                    var className = "";
                    for (var i in data[1]) {
                        var choicePercentage = (data[1][i].count / data[2].sum) * 100;
                        switch (i) {
                            case "0":
                                className = " red";
                                break;
                            case "1":
                                className = " blue";
                                break;
                            case "2":
                                className = " green";
                                break;
                            case "3":
                                className = " yellow";
                                break;
                        }
                        choicesDiv += '<h4>' + data[1][i].pollChoice + '</h4><div class="progress">\n\
<div class="progress-bar' + className + '" role="progressbar" aria-valuenow="' + choicePercentage + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + choicePercentage + '%;">\n\
' + Math.round(choicePercentage * 10) / 10 + '%</div></div>';
                    }
                    $("#pollDisplay").append('<h3>' + data[0].pollQuestion + '</h3>' + choicesDiv + '<div class="pull-right">Total Votes:<strong>' + data[2].sum + '</strong></div>');
                    setCookie("pollId", pollId, 150);
                },
                error: function(xhr, ajaxOptions, thrownError)
                {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
            });
}
var str = "new"
str.split()
$(function() {
    function c() {
        p();
        var e = h();
        var r = 0; //counter
        var u = false;

        l.empty(); //div calendercontent
        while (!u) {
            if (s[r] == e[0].weekday) { //s[] weekdays name to exclude 
                u = true
            } else {
                l.append('<div class="blank"></div>');
                r++
            }
        }

        for (var c = 0; c < 42 - r; c++) {
            if (c >= e.length) {
                l.append()
            } else {

                var v = e[c].day;
                var m = g(new Date(t, n - 1, v)) ? '<div id = "divID-' + v + '" class="today">' : '<div id = "divID-' + v + '">';

                l.append(m + "" + v + "</div>")
            }
        }
        var y = o[n - 1];
        a.find("h1").text(i[n - 1] + " " + t);

        d() //format divs
        //get Month Events by Ajax
        getMonthEvents(n, t)
    }
    //return array of objects containing days numbers and names strating with the week day shifted one
    function h() {
        var e = [];
        for (var r = 1; r < v(t, n) + 1; r++) {
            e.push({
                day: r,
                weekday: s[m(t, n, r)] //s array with day names; weekday contains name of the day
            })
        }
        return e
    }
    //format week heading eg. sat sun...
    function p() {
        f.empty();
        for (var e = 0; e < 7; e++) {
            f.append("<div>" + s[e].substring(0, 3) + "</div>")
        }
    }
    //format calender
    function d() {
        var t;
        var n = $("#calendar").css("width", 100 + "%");
        n.find(t = "#calendar_weekdays, #calendar_content").css("width", 100 + "%").find("div").css({
            width: 14.2 + "%",
            height: 12 + "%",
            "line-height": 30 + "px"
        });
        n.find("#calendar_header").css({
            height: 50 + "px"
        }).find('i[class^="glyphicon"]').css("line-height", 14.2 + "%")
    }


    //month days (28)
    function v(e, t) {

        return (new Date(e, t, 0)).getDate()
    }
    //weekday no eg. 6 the ending of the previous month
    function m(e, t, n) {
        return (new Date(e, t - 1, n)).getDay()
    }
// check isToday 
    function g(e) {
        return y(new Date) == y(e)
    }
    //function to format date (2014/2/23)
    function y(e) {
        return e.getFullYear() + "/" + (e.getMonth() + 1) + "/" + e.getDate()
    }
    //intialize date object
    function b() {
        var e = new Date; //format Sun Feb 23 2014 10:14:23 GMT+0200 (EET)
        t = e.getFullYear(); //format 2014
        n = e.getMonth() + 1 //format 2 (Month Name)
    }
    var e = 480;
    var t = 2014;
    var n = 9;
    var r = [];
    var i = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
    var s = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var o = ["#16a085", "#1abc9c", "#c0392b", "#27ae60", "#FF6860", "#f39c12", "#f1c40f", "#e67e22", "#2ecc71", "#e74c3c", "#d35400", "#2c3e50"];
    var u = $("#calendar");
    var a = u.find("#calendar_header");
    var f = u.find("#calendar_weekdays");
    var l = u.find("#calendar_content");
    b(); //intialize date object
    c();
    a.find('i[class^="glyphicon"]').on("click", function() {
        var e = $(this);
        var r = function(e) {
            n = e == "next" ? n + 1 : n - 1;
            if (n < 1) {
                n = 12;
                t--
            } else if (n > 12) {
                n = 1;
                t++
            }
            c()
        };
        if (e.attr("class").indexOf("left") != -1) {
            r("previous")
        } else {
            r("next")
        }
    })
});

function getMonthEvents(month, year) {
    return $.ajax(
            {
                type: "GET",
                url: baseUrl + "/event/month-events/month/" + month + "/year/" + year,
                dataType: "json",
                success: callback,
                error: function(xhr, ajaxOptions, thrownError)
                {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
            });
}
//call back function for events ajax request
function callback(monthEvents) {
    $("#eventsModals").empty()
    var today = new Date().getDate();
    var todayMonth = new Date().getMonth();
    for (var i in monthEvents) {
        var t = (monthEvents[i].fromDate).split(/[- :]/);
        var day = new Date(t[i], t[1] - 1, t[2], t[3], t[4], t[5]).getDate();
        var month = new Date(t[i], t[1] - 1, t[2], t[3], t[4], t[5]).getMonth();

        $("#divID-" + day).html('<button type="button" class="btn btn-link" data-toggle="modal" data-target="#Modal' + day + '">' + day + '</button>')
        $("#eventsModals").append('<div class="modal fade" id="Modal' + day + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\n\
<div class="modal-dialog">\n\
<div class="modal-content">\n\
<div class="modal-header">\n\
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n\
<h4 class="modal-title" id="myModalLabel">' + monthEvents[i].title + '\n\
<a href="http://os.iti.gov.eg/event/list" title="Add to Calendar" class="addthisevent">\n\
Add to Calendar\n\
<span class="_start">' + monthEvents[i].fromDate + '</span>\n\
<span class="_end">' + monthEvents[i].toDate + '</span>\n\
<span class="_zonecode">47</span>\n\
<span class="_summary">' + monthEvents[i].title + '</span>\n\
<span class="_description">' + (monthEvents[i].description).replace(/(<([^>]+)>)/ig,"") + '</span>\n\
<span class="_location">' + monthEvents[i].place + '</span>\n\
<span class="_date_format">YYYY/MM/DD</span>\n\
</a>\n\
</h4>\n\
</div>\n\
<div class="modal-body">\n\
<strong>Event Title </strong>: ' + monthEvents[i].title + '<br />\n\
<strong>Place </strong>: ' + monthEvents[i].place + '<br />\n\
<strong>Description </strong>: ' + monthEvents[i].description + '<br />\n\
<strong>Strart      </strong>: ' + monthEvents[i].fromDate + '<br />\n\
<strong>End         </strong>: ' + monthEvents[i].toDate + '<br />\n\
</div>\n\
<div class="modal-footer">\n\
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\n\
</div>\n\
</div>\n\
</div>\n\
</div>')

        if (today - 1 === day && todayMonth === month) {
            var StrippedDescription = (monthEvents[i].description).replace(/(<([^>]+)>)/ig, "");
            var cuttedDescription = StrippedDescription.substring(0, 60);
            $("#dayBefore").html('<span>' + day + '</span>\n\
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#Modal' + day + '">' + monthEvents[i].title + '</button>\n\
<p>' + cuttedDescription + ' ...</p><br />')
        }

        if (today === day && todayMonth === month) {
            var StrippedDescription = (monthEvents[i].description).replace(/(<([^>]+)>)/ig, "");
            var cuttedDescription = StrippedDescription.substring(0, 60);
            $("#day").html('<span>' + day + '</span>\n\
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#Modal' + day + '">' + monthEvents[i].title + '</button>\n\
<p>' + cuttedDescription + ' ...</p>')
        }

        if (today + 1 === day && todayMonth === month) {
            var StrippedDescription = (monthEvents[i].description).replace(/(<([^>]+)>)/ig, "");
            var cuttedDescription = StrippedDescription.substring(0, 60);
            $("#dayAfter").html('<span>' + day + '</span>\n\
<button type="button" class="btn btn-link" data-toggle="modal" data-target="#Modal' + day + '">' + monthEvents[i].title + '</button>\n\
<p>' + cuttedDescription + ' ...</p>')
        }
    }




}

if (getCookie("color")) {
    page_style(getCookie("color"))
} else {
    page_style('default')  
}

function page_style(color) {
    var link = document.createElement('link');
    document.getElementById("colorpage").remove();
    link.rel = "stylesheet";
    link.type = "text/css";
    link.id = "colorpage";
    switch (color)
    {
        case 'default':
        case 'red':
            link.href = baseUrl + "/css/cc0000.css";
            setCookie("color", "red", 30);
            break;
        case 'green':
            link.href = baseUrl + "/css/4dc081.css";
            setCookie("color", "green", 30);
            break;
        case 'blue' :
            link.href = baseUrl + "/css/2e75b6.css";
            setCookie("color", "blue", 30);
            break;
        case 'yellow':
            link.href = baseUrl + "/css/ffc000.css";
            setCookie("color", "yellow", 30);
            break;
    }

    document.head.appendChild(link);
}

//set cookie
function setCookie(cname, cvalue, exdays)
{
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";
}

//get cookie
function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0)
            return c.substring(name.length, c.length);
    }
    return "";
}
